package br.com.consultsystems.persistencia.impl.financeiro;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import br.com.consultsystems.dominio.financeiro.Titulo;
import br.com.consultsystems.dominio.tipos.StatusFinanceiro;
import br.com.consultsystems.persistencia.spec.AbstractAdministradoraRepository;
import br.com.consultsystems.persistencia.spec.financeiro.TituloPersistencia;

@Stateless(name = "tituloPersistencia")
public class TituloPersistenciaImpl extends
		AbstractAdministradoraRepository<Titulo> implements TituloPersistencia {

	protected TituloPersistenciaImpl() {
		super(Titulo.class);
	}

	@Override
	public List<Titulo> retrieveByFilter(String nomeCondiminio)
			throws Exception {

		final EntityManager em = getEntityManager();
		final CriteriaBuilder criteriaBuilder = createCriteriaBuilder();
		final CriteriaQuery<Titulo> criteriaQuery = createCriteriaQuery(criteriaBuilder);
		final Root<Titulo> root = createRoot(criteriaQuery);

		final Path<String> pathNome = root.get("condominio").get("nome");
		final Predicate predicateNome = criteriaBuilder.like(pathNome, "%"
				+ nomeCondiminio + "%");

		criteriaQuery.where(predicateNome);

		final TypedQuery<Titulo> typedQuery = em.createQuery(criteriaQuery);

		return typedQuery.getResultList();
	}

	@Override
	public Integer retrieveProximoNumero() {

		/* Gerar o ultimo registro de Restricao encontrado */
		Query query = getEntityManager().createNamedQuery(
				"queryTituloMaxNumero");
		List<Integer> proximoNumero = query.getResultList();

		if (proximoNumero == null || proximoNumero.size() == 0
				|| proximoNumero.get(0) == null) {
			return 1;
		} else {
			return proximoNumero.get(0) + 1;
		}
	}

	@Override
	public List<Titulo> retrieveByCondominio(Long idCondominio)
			throws Exception {
		
		final EntityManager em = getEntityManager();
		final CriteriaBuilder criteriaBuilder = createCriteriaBuilder();
		final CriteriaQuery<Titulo> criteriaQuery = createCriteriaQuery(criteriaBuilder);
		final Root<Titulo> root = createRoot(criteriaQuery);

		final Path<String> pathStatus = root.get("status");
		final Predicate predicateStatus = criteriaBuilder.equal(pathStatus, StatusFinanceiro.ABERTO);

		final Path<Long> pathId = root.get("condominio").get("id");
		final Predicate predicateId = criteriaBuilder.equal(pathId, idCondominio);

		criteriaQuery.where(predicateId, predicateStatus);

		final TypedQuery<Titulo> typedQuery = em.createQuery(criteriaQuery);

		return typedQuery.getResultList();
	}

}
